<?php
/**
 * 微信支付
 */

namespace app\services;

use think\facade\Db;
use utils\WxPay;

/**
 * Class WxPayServices
 * @package app\services
 * @method $this data($data)
 * @method $this trade_type(string $trade_type)
 * @method $this userId(int $userId)
 */
class WxPayServices extends BasePayServices
{

    /**
     * 用户id
     * @var
     */
    protected $userId;

    /**
     * 数据体
     * @var
     */
    protected $data;

    protected static $instance = null;

    public static function instance ()
    {
        if (is_null(self::$instance)) {
            self::$instance = new static();
        }
        return self::$instance;
    }

    /**
     * 微信统一下单
     * @return mixed
     */
    public function getUnifiedOrder ()
    {
        $uid = $this->uid;
        if (!$uid || !$this->data)
            return app('json')->json_error('下单失败');
        list($body, $total_amount, $order_type, $remarks, $trade_type, $pay_way, $voucher_img) = $this->_payConf($uid, $this->data, 2);
        $out_trade_no = rand(1000000000, 9999999999) . (string)date('ymdhis', time()) . (int)microtime(true); // 订单号
        /** @var WxPay $pay */
        $pay = app()->make(WxPay::class);
        $rpm = $pay->unifiedOrder(compact('uid', 'body', 'out_trade_no', 'total_amount'));
        if (!$rpm['flag']) {
            return app('json')->json_error($rpm['msg']);
        }
        $prepay_id = $rpm['data']['partnerid'];
        $this->setPaymentOrder(compact('body', 'out_trade_no', 'total_amount', 'remarks', 'uid', 'trade_type', 'order_type', 'pay_way', 'voucher_img', 'prepay_id'), 2);
        return app('json')->json_success('微信统一下单成功', ['wechat' => $rpm['data']]);
    }

    /**
     * 支付回调
     * @return $this
     */
    public function getNotifyInfo ()
    {
        $pay = new WxPay('notify');
        //$obj = new Request();
        if (isset($this->data['event_type']) && $this->data['event_type'] == 'TRANSACTION.SUCCESS') {
            //$pay->checkSign();
            $notify_info = $pay->notifyDecode($this->data['resource']);
            $this->notify_info = $notify_info;
            $this->pay_status = true;
            $this->pay_way = 2;
        }
        return $this;
    }

    /**
     * 魔术方法
     * @param $name
     * @param $arguments
     * @return $this
     */
    public function __call ($name, $arguments)
    {
        // TODO: Implement __call() method.
        if ($name == 'data') {
            $this->{$name} = $arguments[0];
        } else {
            $this->{$name} = $arguments[0];
        }
        return $this;
    }
}